<template>
  <Dialogdrawerdefect size="720px" :ddtvisible.sync="visible" @close="handleCancel" :title="curStatus === pageStatus.edit ? `编辑短信模板【${title}】`:'新增短信模板'" direction="rtl" :has-modal="false" :modal="false" :close-on-click-modal="true">
    <div class="mianBox cont_box" style="padding-top: 0px !important;" v-loading="loading">
      <el-form inline class="rule-form" ref="form" :model="ruleForm" :rules="rules">
        <el-row>
          <el-col :span="12" v-show="false">
            <el-form-item label="医院名称:" label-width="110px" prop="hospitalName">
              <el-select size="small" class="param-type_input" v-model="ruleForm.hospitalCode" placeholder="请选择" @change="handleChange('hospital')">
                <el-option
                  v-for="(item,index) in mx_hospitalList"
                  :key="index"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="医院编码:" label-width="110px" prop="hospitalCode">
              <el-input size="small" v-model="ruleForm.hospitalCode" placeholder="请输入" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="110px" prop="dep">
              <template slot="label">
                <span>检查部门:</span>
                <el-popover
                  placement="top-start"
                  title=""
                  width="200"
                  trigger="hover">
                  <i slot="reference"></i>
                </el-popover>
              </template>
              <el-select
                @change="handleChange('dep')"
                size="small"
                class="param-type_input"
                clearable
                v-select-create
                filterable
                default-first-option
                v-model="ruleForm.dep"
                placeholder="请选择"
                collapse-tags>
                <el-option
                  v-for="(item,index) in depOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="110px" prop="modality">
              <template slot="label">
                <span>检查设备:</span>
                <el-popover
                  placement="top-start"
                  title=""
                  width="200"
                  trigger="hover">
                  <i slot="reference"></i>
                </el-popover>
              </template>
              <el-select
                size="small"
                class="param-type_input"
                @change="handleChange('modality')"
                v-select-create
                filterable
                default-first-option
                v-model="ruleForm.modality"
                placeholder="请选择"
                clearable
                collapse-tags>
                <el-option
                  v-for="(item,index) in modalityOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="110px" prop="type">
              <template slot="label">
                <span>短信类型:</span>
                <el-popover
                  placement="top-start"
                  title=""
                  width="200"
                  trigger="hover">
                  <i slot="reference"></i>
                </el-popover>
              </template>
              <el-select
                size="small"
                class="param-type_input"
                v-select-create
                allow-create
                filterable
                default-first-option
                v-model="ruleForm.type"
                placeholder="请选择"
                clearable
                collapse-tags>
                <el-option
                  v-for="(item,index) in messageTypeOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="" label-width="110px" prop="isOpen">
              <template slot="label">
                <span>是否启用:</span>
                <el-popover
                  placement="top-start"
                  title=""
                  width="200"
                  trigger="hover"
                  content="启用代表开启此模块短信发送功能，如不发送短信请不要打勾">
                  <i class="el-icon-question pointer" slot="reference"></i>
                </el-popover>
              </template>
              <div style="width: 210px;">
                <el-switch
                  size="small"
                  v-model="ruleForm.isOpen"
                  :active-value="1"
                  :inactive-value="0"
                  active-color="#13ce66"
                >
                </el-switch>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="短信接收方:" label-width="110px" prop="receivePerson">
              <!-- <el-input size="small" v-model="ruleForm.receivePerson" clearable placeholder="请输入"></el-input> -->
              <el-select size="small" style="width: 160px;" v-model="ruleForm.receivePerson" placeholder="请选择" filterable clearable collapse-tags>
                <el-option
                  v-for="(item,index) in receivePersonOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="110px" prop="receiveTel">
              <template slot="label">
                <span>接收电话:</span>
                <el-popover
                  placement="top-start"
                  title=""
                  width="200"
                  trigger="hover"
                  content="若填写接收号码，则只会向其发送短信">
                  <i class="el-icon-question pointer" slot="reference"></i>
                </el-popover>
              </template>
              <el-input size="small" v-model="ruleForm.receiveTel" clearable placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检查部位" label-width="110px" prop="dengjipart">
              <el-select size="small" style="width: 160px;" v-model="ruleForm.dengjipart" multiple placeholder="请选择" filterable clearable collapse-tags>
                <el-option
                  v-for="(item,index) in dengjipartOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扫描方式" label-width="110px" prop="checktype">
              <el-select size="small" style="width: 160px;" v-model="ruleForm.checktype" multiple placeholder="请选择" filterable clearable collapse-tags>
                <el-option
                  v-for="(item,index) in checkTypeOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="年龄区间(岁):" prop="age" label-width="110px">
              <el-input size="small" ref="age" v-model="ruleForm.age" placeholder="开始年龄" clearable onkeyup="this.value = this.value.replace(/[^\d.]/g,'')">
                <!-- <el-select
                  v-model="patientStartAgeUnit"
                  slot="append"
                  style="width: 60px;"
                  clearable
                >
                  <el-option
                    label="岁"
                    value="Y"
                  ></el-option>
                  <el-option
                    label="月"
                    value="M"
                  ></el-option>
                  <el-option
                    label="天"
                    value="D"
                  ></el-option>
                </el-select> -->
              </el-input>
              - <el-input size="small" ref="ageEnd" v-model="ruleForm.ageEnd" placeholder="结束年龄" clearable onkeyup="this.value = this.value.replace(/[^\d.]/g,'')">
                <!-- <el-select
                  v-model="patientEndAgeUnit"
                  slot="append"
                  style="width: 60px;"
                  clearable
                >
                  <el-option
                    label="岁"
                    value="Y"
                  ></el-option>
                  <el-option
                    label="月"
                    value="M"
                  ></el-option>
                  <el-option
                    label="天"
                    value="D"
                  ></el-option>
                </el-select> -->
              </el-input>
            </el-form-item>
            <!-- <el-form-item label="至" prop="ageEnd" label-width="25px" class="ageEnd">
            </el-form-item> -->
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="延迟发送(分钟):" prop="delaytime" label-width="110px">
              <el-input-number style="width: 215px;" controls-position="right" v-model="ruleForm.delaytime" :min="0" :max="60"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="星期:" prop="pattype" label-width="110px">
              <el-select style="width: 160px;" v-model="ruleForm.week" multiple placeholder="请选择" filterable clearable collapse-tags>
                <el-option
                  v-for="item in weekOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="患者类型:" prop="pattype" label-width="110px">
              <el-select style="width: 160px;" v-model="ruleForm.pattype" multiple placeholder="请选择" filterable clearable collapse-tags>
                <el-option
                  v-for="item in patSourceOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="HIS类型:" prop="hisType" label-width="110px">
              <el-select style="width: 160px;" v-model="ruleForm.hisType" placeholder="请选择" filterable clearable>
                <el-option
                  v-for="item in hisTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="预约来源:" prop="appointmentType" label-width="110px">
              <el-select style="width: 160px;" v-model="ruleForm.appointmentType" placeholder="请选择" filterable clearable collapse-tags>
                <el-option
                  v-for="(item,index) in appointmentTypeOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label-width="110px" prop="contentTemplate">
              <template slot="label">
                <span>短信内容:</span>
                <el-popover
                  placement="top-start"
                  title=""
                  width="200"
                  trigger="hover"
                  content="可通过右键选择需要添加的动态字段，如姓名、检查号、预约机房等">
                  <i class="el-icon-question pointer" slot="reference"></i>
                </el-popover>
              </template>
              <div @contextmenu="showContextMenu" @click.stop="isShowContextMenu = false">
                <!-- <textarea ref="targetInput" class="long-info" name="" id="" cols="74" rows="10" placeholder="请输入" @blur="blurEvent" v-model="ruleForm.contentTemplate"></textarea> -->
                <el-input ref="contentInput" class="long-input" type="textarea" size="small" @input="changeChineseContent" @blur="blurEvent" v-model="ruleForm.contentTemplate" placeholder="请输入" :autosize="{ minRows: 8, maxRows: 10}"></el-input>
              </div>
              <div class="context-menu" :style="{ top: contextTop + 'px', left: contextLeft + 'px' }" v-if="isShowContextMenu">
                <el-card class="box-card" style="width: 158px;overflow: scroll;height: 270px;margin-top: 34px;">
                  <div slot="header" class="clearfix">
                    <!-- <span>插入内容</span> -->
                    <el-input suffix-icon="el-icon-search" style="position: absolute; top: 0;left: 4px; width: 158px;" v-model="filterInput" placeholder="输入关键字过滤" @input="fliterContent()"></el-input>
                    <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
                  </div>
                  <div v-for="item in addfilterItem" :key="item.id" :value="item.keyName" :label="item.name">
                    <el-button style="color: black;width: 100%;height: 100%;" class="text-item" type="text" @click.stop="addKeyName(item.id)" v-if="item.name != '暂无任何结果'">{{item.name}}</el-button>
                    <p v-else>{{item.name}}</p>
                  </div>
                </el-card>
              </div>
            </el-form-item>
            <el-form-item label-width="110px" label="对应中文内容:">
              <div>
                <el-input v-model="chineseContent" disabled class="long-input" type="textarea" size="small" placeholder="对应中文内容" :autosize="{ minRows: 2, maxRows: 10}"></el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注:" label-width="110px" prop="remark1">
              <el-input
                class="long-input"
                type="textarea"
                size="small"
                v-model="ruleForm.remark1"
                placeholder="请输入"
                :autosize="{ minRows: 3, maxRows: 4}"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="buttons flex flex-row justify-between align-center">
          <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link cursor">
              更多操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="reset">重置表单</el-dropdown-item>
              <el-dropdown-item command="delete" v-if="curStatus === pageStatus.edit">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- <el-checkbox
            style="margin-left: 10px;"
            v-if="curStatus === pageStatus.add"
            v-model="defaultChecked"
            @change="setDefaultFormData">赋值默认</el-checkbox> -->
          <div class="right-buttons">
            <el-button class="floatR m-l-1" type="primary" size="small" @click="handleConfirm(true)" v-if="curStatus === pageStatus.edit">已此为模板新建</el-button>
            <el-button class="floatR m-l-1" type="primary" size="small" @click="handleConfirm(false)">确定</el-button>
            <el-button class="floatR" size="small" @click="handleClose">取消</el-button>
          </div>
        </div>
      </el-form>
    </div>
  </Dialogdrawerdefect>
</template>
<script>
import Dialogdrawerdefect from '@/components/dialogbox/dialogDrawerDefect'
import { Options } from '@/utils/constant'
import { mapGetters } from 'vuex'
import { PageStatus } from '@/utils/constant'
import { getItemListFunc } from '@/api/common'
import {
  getDepList,
  getModalityList,
  getBigPartList,
  addMessage,
  deleteMessage,
  editMessage,
  getItemGroupList,
  getMessageModel
} from '@/api/api.js'
export default {
  props: {
    // 是否弹出右侧
    showRight: {
      Boolean,
      default: false
    },
    // 判断是新增还是编辑
    curStatus: {
      String,
      default: ''
    },
    // 标题
    title: {
      String,
      default: ''
    },
    rowData: {
      Object,
      default: () => {}
    },
    hospitalCode: {
      String,
      default: ''
    }
  },
  computed: {
    ...mapGetters(['appointmentTypeOptions', 'hisTypeOptions'])
  },
  data() {
    return {
      addInfoItem: [],
      addfilterItem: [],
      filterInput: '',
      pageStatus: PageStatus,
      visible: false,
      ruleForm: {
        hospitalCode: '',
        dep: '',
        week: [],
        modality: '',
        type: '',
        isOpen: false,
        receivePerson: '',
        contentTemplate: '',
        remark1: '',
        dengjipart: [],
        checktype: '',
        pattype: [], // 值域：1-门诊；2-住院；3-体检；4-绿检；5-急诊
        age: '', // 年龄 21Y/8M/9D/10H
        ageEnd: '', // 年龄 21Y/8M/9D/10H
        delaytime: 0,
        receiveTel: '',
        appointmentType: '',
        hisType: ''
      },
      weekOptions: [{ 'value': 1, 'label': '星期一' }, { 'value': 2, 'label': '星期二' }, { 'value': 3, 'label': '星期三' }, { 'value': 4, 'label': '星期四' }, { 'value': 5, 'label': '星期五' }, { 'value': 6, 'label': '星期六' }, { 'value': 7, 'label': '星期日' }],
      receivePersonOptions: ['患者', '护士', '申请医生', '审核医生', '负责人'],
      // patientStartAgeUnit: 'Y', // 21Y/8M/9D/10H
      // patientEndAgeUnit: 'Y', // 21Y/8M/9D/10H
      chineseContent: '',
      isShowContextMenu: false, // 控制上下文菜单的显示与隐藏
      contextTop: 0, // 上下文菜单的top值
      contextLeft: 0, // 上下文菜单的left值
      itemId: '', // 被点击元素的ID
      itemName: '', // 被点击元素的名称
      itemUrl: '', // 被点击元素对应的URL
      blurStartIndex: null, // 记录光标开始位置
      blurEndIndex: null, // 记录光标结束位置
      patSourceOptions: Options.patientTypeItemOptions.map(item => ({ 'value': item.value, 'label': item.label })),
      depOptions: [],
      checkTypeOptions: [],
      modalityOptions: [],
      messageTypeOptions: [],
      rules: {
        dep: { required: true, message: '请选择检查部门', trigger: 'blur' },
        type: { required: true, message: '请输入短信类型', trigger: 'blur' },
        age: {
          required: false,
          message: '开始年龄要小于结束年龄',
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (parseInt(this.ruleForm.ageEnd) >= parseInt(value) || (isNaN(parseInt(this.ruleForm.age)) && isNaN(parseInt(this.ruleForm.ageEnd)))) {
              // console.error('来这里了嘛')
              callback()
            } else {
              callback(new Error('开始年龄要小于结束年龄'))
            }
          }
        }
      },
      dengjipartOptions: '',
      loading: false,
      // 赋值默认值
      defaultChecked: true
    }
  },
  async mounted() {
    this.visible = this.showRight
    await this.$store.dispatch('settings/set_appointTypeOptions', { HospitalCode: this.ruleForm.hospitalCode || this.hospitalCode, type: '预约来源' })
    await this.$store.dispatch('settings/set_hisTypeOptions', { HospitalCode: this.ruleForm.hospitalCode || this.hospitalCode, type: 'HIS类型' })
    // this.ruleForm.hospitalCode = this.$store.state.user.hospitalCode
    // this.getAllListData()
  },
  watch: {
    async visible(val) {
      this.$emit('update:showRight', val)
      this.isShowContextMenu = false
      if (val) {
        this.ruleForm.hospitalCode = this.hospitalCode
        this.$nextTick(() => {
          if (this.rowData) {
            // this.getMessageDetail(this.rowData)
          } else {
            this.setDefaultFormData()
          }
        })
      }
    },
    showRight(val) {
      this.visible = val
    },
    async rowData(val) {
      this.isShowContextMenu = false
      if (val && this.visible) {
        await this.getMessageDetail(this.rowData)
      } else {
        this.setDefaultFormData()
      }
      this.$getHospitalList()
      this.getAllListData()
    },
    formData(data) {
      if (data && this.visible) {
        this.setDefaultFormData()
      }
    },
    hospitalCode: {
      handler(val) {
        if (val && this.visible) {
          this.ruleForm.hospitalCode = val
          this.handleChange('hospital')
        }
      },
      immediate: true
    }
  },
  components: { Dialogdrawerdefect },
  beforeDestroy() {
    this.timeout01 && clearTimeout(this.timeout01)
    this.timeout02 && clearTimeout(this.timeout02)
    this.timeout03 && clearTimeout(this.timeout03)
  },
  methods: {
    blurEvent(e) {
      this.blurStartIndex = e.srcElement.selectionStart
      e.srcElement.selectionEnd && this.blurStartIndex < e.srcElement.selectionEnd ? this.blurEndIndex = e.srcElement.selectionEnd : this.blurEndIndex = 0
      // console.error('this.blurStartIndex', this.blurStartIndex) // 光标所在的位置
    },
    getMessageDetail(messageParam) {
      this.loading = true
      const params = {
        hospitalCode: this.ruleForm.hospitalCode,
        id: messageParam.id
      }
      return new Promise(resolve => {
        getMessageModel(params).then(res => {
          if (res.code === 10000) {
            let messageInfoSolve = res.content
            messageInfoSolve.pattype = messageInfoSolve.pattype ? messageInfoSolve.pattype.split(',') : []
            messageInfoSolve.checktype = messageInfoSolve.checktype ? messageInfoSolve.checktype.split(',') : []
            messageInfoSolve.dengjipart = messageInfoSolve.dengjipart ? messageInfoSolve.dengjipart.split(',') : []
            messageInfoSolve.week = messageInfoSolve.week ? messageInfoSolve.week.split(',') : []
            messageInfoSolve.hospitalCode = this.ruleForm.hospitalCode
            messageInfoSolve.id = messageInfoSolve.id.toString()
            this.ruleForm = JSON.parse(JSON.stringify(messageInfoSolve))
            this.loading = false
          }
          resolve(res)
        })
      })
    },
    showContextMenu(e) {
      event.preventDefault()
      this.isShowContextMenu = true
      this.contextTop = e.clientY
      this.contextLeft = e.clientX
      // 获取被点击元素的信息（此处仅示意）
      const targetElement = e.target
      this.itemId = targetElement.dataset.id || ''
      this.itemName = targetElement.innerText || ''
      this.itemUrl = targetElement.href || ''
    },
    addKeyName(id) {
      // 先获得要添加的内容
      const filteredItems = this.addInfoItem.filter(item => item.id === id)
      let targetInput = this.$refs.contentInput.$el.querySelector('textarea')
      let startIndex = this.blurStartIndex
      let endIndex = this.blurEndIndex
      let newEndIndex = parseInt(startIndex + filteredItems[0].keyName.length)
      // 如果开始光标小于结束光标，则由开始光标到结束光标进行内容替换，将光标最后锁定在加的内容最后
      if (startIndex < endIndex) {
        this.ruleForm.contentTemplate = this.ruleForm.contentTemplate.slice(0, startIndex) + filteredItems[0].keyName + this.ruleForm.contentTemplate.slice(endIndex)
        this.chineseContent = this.ruleForm.chineseContent.slice(0, startIndex) + '[' + filteredItems[0].name + ']' + this.ruleForm.chineseContent.slice(endIndex)
        // this.$nextTick(() => {
        //   targetInput.focus()
        //   targetInput.setSelectionRange(newEndIndex, newEndIndex)
        // })
        this.blurEndIndex = 0
      } else {
        // 如果开始光标大于或等于结束光标，则在开始光标后直接顺延添加
        this.ruleForm.contentTemplate = this.ruleForm.contentTemplate === null || this.ruleForm.contentTemplate === '' ? filteredItems[0].keyName : this.ruleForm.contentTemplate.slice(0, startIndex) + filteredItems[0].keyName + this.ruleForm.contentTemplate.slice(startIndex)
        this.chineseContent = this.chineseContent === null || this.chineseContent === '' ? '[' + filteredItems[0].name + ']' : this.chineseContent.slice(0, startIndex) + '[' + filteredItems[0].name + ']' + this.chineseContent.slice(startIndex)
        // this.$nextTick(() => {
        //   targetInput.focus()
        //   targetInput.setSelectionRange(newEndIndex, newEndIndex)
        // })
      }
      this.$nextTick(() => {
        targetInput.focus()
        targetInput.setSelectionRange(newEndIndex, newEndIndex)
      })
    },
    fliterContent() {
      if (this.filterInput != '') {
        // console.error('this.filterInput', this.filterInput)
        this.addfilterItem = this.addInfoItem.filter(item => item.name.indexOf(this.filterInput) !== -1)
        // console.error('this.addfilterItem', this.addfilterItem)
        if (this.addfilterItem.length === 0) {
          this.addfilterItem = [{ id: 0, name: '暂无任何结果', keyName: null }]
        }
      } else {
        this.addfilterItem = this.addInfoItem
      }
    },
    // 设置赋值默认值
    setDefaultFormData() {
      const data = this.ruleForm
      if (data && this.visible && this.defaultChecked) {
        this.ruleForm.dep = ''
        this.ruleForm.modality = ''
        this.ruleForm.dengjipart = []
        this.ruleForm.pattype = []
        this.ruleForm.type = ''
        this.ruleForm.receivePerson = ''
        this.ruleForm.receiveTel = ''
        this.ruleForm.age = ''
        this.ruleForm.ageEnd = ''
        this.ruleForm.remark1 = ''
        this.ruleForm.contentTemplate = ''
        this.ruleForm.checktype = []
        this.ruleForm.delaytime = 0
        this.ruleForm.isOpen = 0
        // this.getAllListData()
      }
    },
    handleCommand(command) {
      switch (command) {
        case 'reset':
          this.handleReset()
          break
        case 'delete':
          this.delete()
          break
        default:
          break
      }
    },
    async handleChange(val) {
      switch (val) {
        case 'hospital':
          this.depOptions = []
          this.modalityOptions = []
          this.dengjipartOptions = []
          this.messageTypeOptions = []
          this.checkTypeOptions = []
          this.ruleForm.dep = ''
          this.ruleForm.modality = ''
          this.ruleForm.dengjipart = []
          this.ruleForm.type = ''
          this.ruleForm.checktype = ''
          this.getAllListData()
          break
        case 'dep':
          this.modalityOptions = []
          this.dengjipartOptions = []
          this.ruleForm.modality = ''
          this.ruleForm.dengjipart = []
          try {
            await this.getModalityOptions()
            await this.getBigPartOptions()
          } catch (err) {
            console.log(err)
          }
          break
        case 'modality':
          this.dengjipartOptions = []
          this.ruleForm.dengjipart = []
          try {
            await this.getBigPartOptions()
          } catch (err) {
            console.log(err)
          }
          break
        default:
          break
      }
    },
    delete() {
      /* 删除 */
      this.$confirm('此操作将永久删除该短信, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteData()
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    deleteData() {
      deleteMessage({ id: this.ruleForm.id, hospitalCode: this.ruleForm.hospitalCode }).then((res) => {
        if (res.code === 10000) {
          this.$message.success('删除成功')
          this.handleClose()
          this.refresh()
        }
      })
    },
    handleClose() {
      this.$emit('update:showRight', false)
      this.handleCancel()
    },
    handleCancel() {
      // 关闭弹窗
      this.handleReset()
    },
    handleReset() {
      /* 重置 */
      // this.$refs.form.clearValidate()
      // this.$refs.form.resetFields()
      // this.$refs.form.clearValidate()
      // this.curStatus === this.pageStatus.edit ? this.ruleForm = Object.assign(this.ruleForm, this.saveOldForm) : this.setDefaultFormData()
      this.setDefaultFormData()
      // console.error('this.form', this.ruleForm)
    },
    // 获取下拉数据
    getAllListData() {
      const that = this
      return new Promise(async (resolve, reject) => {
        const res = Promise.all([
          that.getDepOptions(),
          that.getModalityOptions(),
          // that.getMessageType(),
          that.getBigPartOptions(),
          that.getcheckType(),
          that.getMessageInfo(),
          that.getItemGroupList()
        ])
        if (res) {
          resolve(true)
        } else {
          reject(false)
        }
      })
    },
    // 获取检查部门数据
    getDepOptions() {
      let params = {
        hospitalCode: this.ruleForm.hospitalCode
      }
      return new Promise(async resolve => {
        await getDepList(params).then(res => {
          if (res.code === 10000) {
            this.depOptions = res.content.list
            if (this.depOptions.length === 1) {
              this.ruleForm.dep = this.depOptions[0]
            }
            resolve(res)
          }
        })
      })
    },
    // 获取设备类型数据
    getModalityOptions() {
      let params = {
        hospitalCode: this.ruleForm.hospitalCode,
        dep: this.ruleForm.dep
      }
      // console.error('this.ruleForm.dep', this.ruleForm.dep)
      return new Promise(async resolve => {
        await getModalityList(params).then(res => {
          if (res.code === 10000) {
            this.modalityOptions = res.content.list
            // if (this.modalityOptions.length === 1) {
            //   this.ruleForm.modality = this.modalityOptions[0]
            // }
            // this.ruleForm.modality = this.modality[0]
          }
          resolve(res)
        })
      })
    },
    async getItemGroupList() {
      let data = {
        HospitalCode: this.ruleForm.hospitalCode,
        type: '短信类型'
      }
      getItemGroupList(data).then(res => {
        if (res && res.code == 10000) {
          this.messageTypeOptions = res.content.list
        }
      })
    },
    // 短信模板
    async getMessageInfo() {
      let data = {
        HospitalCode: this.ruleForm.hospitalCode,
        type: '短信模板'
      }
      getItemListFunc(data).then(res => {
        let messageType = res.map(_item => {
          let newObj = {}
          newObj['keyName'] = _item.itemValue
          newObj['name'] = _item.item
          newObj['id'] = _item.id
          return newObj
        }).filter(ap => ap)
        this.addfilterItem = this.addInfoItem = messageType
        this.getChineseContent(this.addInfoItem)
        // const messageType = res.map(_item => {_item.item}).filter(ap => ap)
        // console.error('messageType', messageType)
        // console.error('来这里了', res)
      })
    },
    // 扫描方式
    async getcheckType() {
      let data = {
        HospitalCode: this.ruleForm.hospitalCode,
        type: '扫描方式'
      }
      getItemGroupList(data).then(res => {
        if (res && res.code == 10000) {
          this.checkTypeOptions = res.content.list
        }
      })
    },
    // 获取大部位数据
    getBigPartOptions() {
      const params = {
        hospitalCode: this.ruleForm.hospitalCode,
        Dep: this.ruleForm.dep,
        Modality: this.ruleForm.modality
      }
      return new Promise(resolve => {
        getBigPartList(params).then(res => {
          if (res.code === 10000) {
            const dengjipartOptions = res.content.list
            this.dengjipartOptions = dengjipartOptions
          }
          resolve(res)
        })
      })
    },
    handleConfirm(addFlag) {
      this.$refs.form.validate((valid, object) => {
        if (valid) {
          if (this.curStatus === this.pageStatus.add || addFlag) {
            /* 新增保存 */
            this.addSave(addFlag)
          } else {
            /* 编辑保存 */
            this.editSave()
          }
        } else {
          this.timeout01 = setTimeout(() => {
            var isError = document.getElementsByClassName('is-error')
            isError[0].querySelector('input').focus()
          }, 100)
          for (let k in object) {
            this.$message.warning(object[k][0].message)
            return
          }
        }
      })
    },
    addSave(addFlag) {
      /* 新增保存 */
      this.loading = true
      // let hospital = this.mx_hospitalList.find((e) => {
      //   return e.code === this.ruleForm.hospitalCode
      // })
      let data = {
        ...this.ruleForm,
        checktype: this.ruleForm.checktype.join(','),
        dengjipart: this.ruleForm.dengjipart.join(','),
        isOpen: (!!this.ruleForm.isOpen).toString().charAt(0).toUpperCase() + (!!this.ruleForm.isOpen).toString().slice(1),
        pattype: this.ruleForm.pattype === null ? '' : this.ruleForm.pattype.join(','),
        week: this.ruleForm.week.join(','),
        type: this.ruleForm.type
      }
      if (!isNaN(parseInt(this.ruleForm.age)) && !isNaN(parseInt(this.ruleForm.ageEnd))) {
        data.age = parseInt(this.ruleForm.age)
        data.ageEnd = parseInt(this.ruleForm.ageEnd)
      } else {
        delete data.age
        delete data.ageEnd
      }
      addMessage(data).then((res) => {
        this.loading = false
        if (res.code === 10000) {
          if (addFlag) {
            this.$message.success('新增成功，当前编辑短信为：' + this.ruleForm.type)
            this.ruleForm.id = res.content.id
          } else {
            this.$message.success('保存成功')
          }
          this.$emit('refresh')
        }
      }).catch(() => {
        this.loading = true
        this.timeout02 = setTimeout(() => {
          this.loading = false
        }, 500)
      })
    },
    editSave() {
      // /* 编辑保存 */
      this.loading = true
      // let hospital = this.mx_hospitalList.find((e) => {
      //   return e.code === this.ruleForm.hospitalCode
      // })
      let data = {
        ...this.ruleForm,
        checktype: this.ruleForm.checktype.join(','),
        dengjipart: this.ruleForm.dengjipart.join(','),
        isOpen: (!!this.ruleForm.isOpen).toString().charAt(0).toUpperCase() + (!!this.ruleForm.isOpen).toString().slice(1),
        pattype: this.ruleForm.pattype === null ? '' : this.ruleForm.pattype.join(','),
        week: this.ruleForm.week.join(','),
        type: this.ruleForm.type
      }
      if (!isNaN(parseInt(this.ruleForm.age)) && !isNaN(parseInt(this.ruleForm.ageEnd))) {
        data.age = parseInt(this.ruleForm.age)
        data.ageEnd = parseInt(this.ruleForm.ageEnd)
      } else {
        delete data.age
        delete data.ageEnd
      }
      editMessage(data).then((res) => {
        this.loading = false
        if (res.code === 10000) {
          this.$message.success(res.message)
          this.$emit('refresh')
        }
      }).catch(() => {
        this.loading = true
        this.timeout03 = setTimeout(() => {
          this.loading = false
        }, 500)
      })
    },
    changeStatus(status) {
      this.ruleForm.isOpen = status
    },
    ruleFormClean(oldRuleForm) {
      oldRuleForm.isOpen = oldRuleForm.isOpen === 'True' ? 1 : 0
      oldRuleForm.checktype = typeof (oldRuleForm.checktype) == 'string' ? (oldRuleForm.checktype.includes(',') ? oldRuleForm.checktype.split(',') : [oldRuleForm.checktype]) : []
      oldRuleForm.week = typeof (oldRuleForm.week) == 'string' ? (oldRuleForm.week.includes(',') ? oldRuleForm.week.split(',') : [oldRuleForm.week]) : []
      oldRuleForm.dengjipart = typeof (oldRuleForm.dengjipart) == 'string' ? (oldRuleForm.dengjipart.includes(',') ? oldRuleForm.dengjipart.split(',') : [oldRuleForm.dengjipart]) : []
      oldRuleForm.hospitalCode = oldRuleForm.hospitalCode ? oldRuleForm.hospitalCode : this.hospitalCode
      oldRuleForm.id ? oldRuleForm.id = oldRuleForm.id.toString() : null
      // let newData = oldRuleForm.pattype.map((item, index) => {
      //   return { value: index + 1, label: item }
      // })
      // console.error('oldRuleForm.pattype', oldRuleForm.pattype)
      if (typeof oldRuleForm.pattype === 'string') {
        // 只有在 oldRuleForm.pattype 是字符串类型时才执行 split 操作
        oldRuleForm.pattype = oldRuleForm.pattype.split(',')
        // console.error('splitArray', oldRuleForm.pattype)
        // 其他操作...
      } else {
        // 处理 oldRuleForm.pattype 不是字符串的情况，比如设置一个默认值或者进行其他逻辑处理
      }
      // console.error('newData', this.patSourceOptions, newData)
      // oldRuleForm.pattype = newData
      return oldRuleForm
    },
    refresh() {
      // 本地缓存排班管理的机房选择数据重置默认选项
      // this.$store.dispatch('user/getDefaultCheckRoomTree')
      // this.$store.dispatch('user/resetDefaultCheckRoom', [])
      // console.error('来这里了嘛')
      this.getAllListData()
      this.$emit('refresh')
    },
    getChineseContent(addInfoItem) {
      let contentCopy = this.ruleForm.contentTemplate
      const regex1 = /\[(.*?)\]/g
      const matches = [...contentCopy.matchAll(regex1)]
      const contents = matches.map(match => '[' + match[1] + ']')
      console.log(contents)
      addInfoItem.forEach(element => {
        if (contents.includes(element.keyName)) {
          contentCopy = contentCopy.replace(element.keyName, '[' + element.name + ']')
        }
      })
      this.chineseContent = contentCopy

      // let contentCopy = this.ruleForm.contentTemplate
      // const regex = /\[([A-Z]+)\]/g
      // let match
      // while ((match = regex.exec(contentCopy)) !== null) {
      //   addfilterItem.forEach(element => {
      //     if (element.keyName === '[' + match[1] + ']') {
      //       contentCopy = contentCopy.replace(match[1], element.name)
      //     }
      //   })
      //   // console.error(match[1])
      // }
      // this.chineseContent = contentCopy
    },
    changeChineseContent() {
      // console.error('addfilterItem', this.addfilterItem)
      this.getChineseContent(this.addInfoItem)
    }
  }
}
</script>
<style lang='scss' scoped>
.add_department{
  font-size: 14px;
  cursor: pointer;
  color: #00c0ef;
  &:hover{
    opacity: 0.6;
  }
}
/deep/ .el-form-item__label{
  text-align: right;
}
.mianBox{
  /deep/ .el-input{
    width: 215px;
  }
  .long-input{
    width: 555px;
    /deep/ .el-input{
        width: 500px;
    }
  }
  .name{
    font-weight: bold;
  }
  .el-form--inline .el-form-item{
    margin-right:0px;
    margin-bottom: 16px;
  }
  /deep/ .el-form-item__label{
    line-height: 32px;
  }
  /deep/ .el-form-item__content{
    line-height: 32px;
  }
  .buttons{
    width: 100%;
    .el-dropdown{
      color: #00c0ef;
    }
  }
  .pointer {
    cursor: pointer;
  }
}
/* 自定义上下文菜单样式 */
.context-menu {
  position: fixed; /* 或者 absolute */
  /* background-color: #fff; */
  /* border: 1px solid #ccc; */
  padding: 5px;
  z-index: 500;
}
.box-card >>> .el-card__body,.box-card >>> .el-card__header{
  text-align:center;
  padding: 0px;
}
.long-info {
  width: 100%;
  border: 0.3px solid #dcdfe6;
  border-radius: 4px;
  padding: 5px 15px;
  padding: 10px;
  font-size: 14px;
  line-height: 1.5;
  font-size: inherit;
  max-height: 300px; /* 设置最大高度 */
  transition: border-color .2s cubic-bezier(.645,.045,.355,1);
  overflow: auto; /* 超出最大高度时显示滚动条 */
}
.long-info:focus {
  border: 0.3px solid #dcdfe6;/* 将边框宽度设置为1px */
  /* box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2); */
  outline-color: #00C0EF;
  outline-width: 0.2px;
  outline-style: solid;
}
/* 输入框placeholder的样式 */
.long-info::placeholder {
  color: #c9c9c9; /* placeholder文本颜色 */
}
.long-info {
  resize:vertical; /* 只能水平调整元素大小 */
}
/deep/ .text-item:hover{
  background-color: #dcdfe6;
}
.text-item{
  color: black;
  border-bottom:1px solid #ebeef5;
  transition: 0.5s;
  cursor: pointer;
}
.cursor{
  cursor: pointer;
}
</style>

